package com.mangowang.module.main.ui;


import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.fragment.app.FragmentActivity;

import com.example.havi.helper.ChatHelper;
import com.example.havi.interfaces.LoginCallBack;
import com.example.havi.ui.ChatActivity;
import com.google.protobuf.InvalidProtocolBufferException;
import com.mangowang.lib.common.App;
import com.mangowang.lib.common.base.BaseFragment;
import com.mangowang.lib.common.bean.UserBean;
import com.mangowang.lib.common.help.GlideHelper;
import com.mangowang.lib.common.help.PermissionHelper;
import com.mangowang.lib.common.help.UserHelper;
import com.mangowang.lib.common.net.Apis;
import com.mangowang.lib.common.net.NetworkManager;
import com.mangowang.lib.common.net.WebApis;
import com.mangowang.lib.common.net.interfaces.OnRequestCallBack;
import com.mangowang.lib.common.proto.AgentPolicy;
import com.mangowang.lib.common.proto.Index;
import com.mangowang.lib.common.proto.MemberOuterClass;
import com.mangowang.lib.common.util.StringUtil;
import com.mangowang.lib.common.bean.ServiceBean;
import com.mangowang.module.main.web.ui.WebViewActivity;
import com.mangowang.module.main.R;
import com.mangowang.module.main.R2;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * Created by Administrator on 2018/2/2 0002.
 */

public class MineFragment extends BaseFragment {


    Unbinder unbinder; // bufferKnife绑定

    @BindView(R2.id.tv_name)
    TextView tv_name;
    @BindView(R2.id.iv_head)
    ImageView iv_head;
    @BindView(R2.id.tv_phone)
    TextView tv_phone;

    @BindView(R2.id.mine_ll_one)
    LinearLayout mine_ll_one;


    @BindView(R2.id.mine_ll_two)
    LinearLayout mine_ll_two;


    @BindView(R2.id.mine_ll_three)
    LinearLayout mine_ll_three;

    @BindView(R2.id.mine_ll_four)
    LinearLayout mine_ll_four;

    @BindView(R2.id.mine_ll_five)
    LinearLayout mine_ll_five;


    @BindView(R2.id.mine_ll_six)
    LinearLayout mine_ll_six;


    @BindView(R2.id.mine_ll_seven)
    LinearLayout mine_ll_seven;


    @BindView(R2.id.tv_level_name)
    TextView tv_level_name;
    @BindView(R2.id.tv_level_tra)
    TextView tv_level_tra;
    @BindView(R2.id.tv_level_next)
    TextView tv_level_next;
    @BindView(R2.id.my_progress)
    ProgressBar my_progress;
    @BindView(R2.id.rv_level)
    RelativeLayout rv_level;

    @BindView(R2.id.iv_edit)
    ImageView iv_edit;


    @BindView(R2.id.tv_time)
    TextView tv_time;


    private String ImgUpgrade;
    private String keFuPhone;


    @Override
    protected int getLayoutId() {

        return R.layout.mine_fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    protected void initView() {

        loadInfo();
        initListener();

    }

    private void initListener() {
        mine_ll_one.setOnClickListener(v -> startActivity(QrActivity.class));
        mine_ll_two.setOnClickListener(v -> startActivity(BankCardActivity.class));
        mine_ll_three.setOnClickListener(v -> {
            boolean login = ChatHelper.getInstance().isLogin();
            if (login) {
                // 打开客服聊天
                ServiceBean keFuInfo = UserHelper.getKeFuInfo();
                ChatActivity.startActivity(mContext, keFuInfo.getMember_id() + "", keFuInfo.getMember_name(), keFuInfo.getMember_avatar(), keFuInfo.getChat_id(), keFuInfo.getMember_mobile());
            } else {
                showToast("聊天登录中");
                App.getChatHelper().login(UserHelper.getUser().getChat_id(), UserHelper.getUser().getChat_pwd(), new LoginCallBack() {
                    @Override
                    public void onSuccess() {
                        //判断是否为客服
                        // 打开客服聊天
                        ServiceBean keFuInfo = UserHelper.getKeFuInfo();
                        mContext.runOnUiThread(() -> showToast("人工客服回复时间：工作日9:00-12:00；13:30-18:00"));
                        ChatActivity.startActivity(mContext, keFuInfo.getMember_id() + "", keFuInfo.getMember_name(), keFuInfo.getMember_avatar(), keFuInfo.getChat_id(), keFuInfo.getMember_mobile());
                    }

                    @Override
                    public void onError(int code, String message) {
                        mContext.runOnUiThread(() -> showToast("聊天暂时登录失败"));
                    }
                });
            }
        });

        mine_ll_four.setOnClickListener(v -> {
            PermissionHelper.getInstance().getPermission((FragmentActivity) mContext, new PermissionHelper.PermissionCallBack() {
                @Override
                public void onSuccess() {
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + keFuPhone));
                    startActivity(intent);
                }

                @Override
                public void onFail() {

                }
            }, Manifest.permission.CALL_PHONE);


        });
        mine_ll_five.setOnClickListener(v -> WebViewActivity.startActivity(mContext, WebApis.about));
        mine_ll_six.setOnClickListener(v -> startActivity(FeedBackActivity.class));
        mine_ll_seven.setOnClickListener(v -> startActivity(SettingActivity.class));
        rv_level.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, LevelActivity.class);
                startActivity(intent);
            }
        });

        iv_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(EditUserInfoActivity.class);

            }
        });


    }

    private void loadInfo() {
        NetworkManager.INSTANCE.post(Apis.memberDataInfo, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                MemberOuterClass.Member member = MemberOuterClass.Member.parseFrom(bytes);
                Log.e("mango", "onOk: " + member);
                UserBean userInfoBean = new UserBean();
                userInfoBean.setMember_id(member.getMemberId());
                userInfoBean.setMember_name(member.getMemberName());
                userInfoBean.setMember_mobile(member.getMemberMobile());
                userInfoBean.setMember_avatar(member.getMemberAvatar());
                userInfoBean.setMember_level(member.getMemberLevel());
                userInfoBean.setIs_bank(member.getIsBank());
                userInfoBean.setIs_approve(member.getIsApprove());
                userInfoBean.setIs_paypwd(member.getIsPaypwd());
                userInfoBean.setTruename(member.getTruename());
                userInfoBean.setIdcard(member.getIdcard());
                userInfoBean.setAge(member.getEvolution().getAge());
                userInfoBean.setSex(member.getEvolution().getSex());
                userInfoBean.setEvolution_city(member.getEvolution().getEvolutionCity());
                userInfoBean.setEvolution_address(member.getEvolution().getEvolutionAddress());
                userInfoBean.setEvolution_city_id(member.getEvolution().getEvolutionCityId());
                UserHelper.syncCurrentUserInfo(userInfoBean);   //同步个人信息

                tv_name.setText(UserHelper.getUser().getTruename());
                tv_phone.setText(StringUtil.PhoneToPass(UserHelper.getUser().getMember_mobile()));
                GlideHelper.INSTANCE.loadAvatar(mContext, iv_head, UserHelper.getUser().getMember_avatar());
            }

            @Override
            public void onError(int code, String errorMessage) {

            }
        });

        NetworkManager.INSTANCE.post(Apis.show_policy, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                AgentPolicy.show_policy member = AgentPolicy.show_policy.parseFrom(bytes);

                tv_level_name.setText(member.getLevelName());
                tv_level_tra.setText("当前月交易 ¥" + member.getAmount());
                tv_level_next.setText("下一等级 " + StringUtil.setMoneyString(member.getLengthList().get(1).getAmount(), true));

                int floats = (int) (Float.parseFloat(member.getFloat()) * 100);
                if (floats >= 100) {
                    tv_level_next.setVisibility(View.INVISIBLE);
                }
                my_progress.setProgress(floats);
                ImgUpgrade = member.getImgUpgrade();
            }

            @Override
            public void onError(int code, String errorMessage) {

            }
        });

        // 加载客服数据
        NetworkManager.INSTANCE.post(Apis.get_kfu_info, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                Index.get_kfu_info kefu_message = Index.get_kfu_info.parseFrom(response);
                ServiceBean serviceBean = new ServiceBean();
                serviceBean.setMember_id(kefu_message.getMemberId());
                serviceBean.setMember_name(kefu_message.getMemberName());
                serviceBean.setMember_mobile(kefu_message.getMemberMobile());
                serviceBean.setMember_avatar(kefu_message.getMemberAvatar());
                serviceBean.setChat_id(kefu_message.getChatId());
                serviceBean.setChat_pwd(kefu_message.getChatPwd());
                tv_time.setText(kefu_message.getTime());
                UserHelper.saveKeFuUserInfo(serviceBean);
                keFuPhone = serviceBean.getMember_mobile();
            }

            @Override
            public void onError(int errorCode, String errorMessage) {

            }
        });

    }

    @Override
    protected void init() {

    }
}
